<?php
/**
 * Created by PhpStorm.
 * User: Tom
 * Date: 2018/7/14
 * Time: 14:42
 */
function genhtml($abc)
{
    echo $abc."---hello world".date("Y/m/d H:i:s");
    return;
}

function danxuan($timu)
{

    //选项模板


    $tmid=$timu['id'];
    $xuan=$timu['xuan'];    //是否单选
    $i=1;
    $xx_html='';                //选项html
    $type_html="type='3'";      //类型
    foreach($timu['xuanxiang'] as $key=>$value)
    {
        $html_id=$tmid .'_'.$i;
        $html_lbl=chr(64+$i);



        //单选
        if($xuan==1)
        {
            $xx_html.="
            <div class='ui-radio'>
                <span class='jqradiowrapper'>
                    <input type='radio' value='{$key}' id='q{$html_id}' name='q{$tmid}' style='display:none;' />
                    <a class='jqradio' href='javascript:;'></a>
                </span>
                <div class='label' for='q{$html_id}'>{$html_lbl}.{$value}</div>
            </div>
            ";
        }
        if($xuan==2)
        {
            if(is_array($value))
            {
              //  dump($value);die("49");
                $title=$value['text'];  //选填的标题
                $xx_html .= "
                    <div class='ui-checkbox'>
                        <span class='jqcheckwrapper'>
                            <input type='checkbox' value='{$key}' id='q{$html_id}' name='q{$tmid}' style='display:none;' />
                            <a class='jqcheck' href='javascript:;'></a>
                        </span>
                        <div class='label' for='q{$html_id}'>{$html_lbl}.{$title}</div>
                
                         <div class='ui-text' style='position:relative;'>
                          <input type='text' rel='q{$html_id}' id='tqq{$html_id}' class='OtherText'>
                         </div>
                        
                    </div>
            ";

            }
            else
            {
                $xx_html .= "
            <div class='ui-checkbox'>
            <span class='jqcheckwrapper'>
                <input type='checkbox' value='{$key}' id='q{$html_id}' name='q{$tmid}' style='display:none;' />
                <a class='jqcheck' href='javascript:;'></a>
            </span>
                <div class='label' for='q{$html_id}'>{$html_lbl}.{$value}</div>
            </div>
            ";

            }
            $type_html = "type='4'";

        }

        $i++;
    }

    if($timu['lieshu']==2)
    {
        $xx_html="<div class='ui-controlgroup two_column'>{$xx_html}</div>";
    }
    else
    {
        $xx_html="<div class='ui-controlgroup'> {$xx_html}</div>";
    }

    //必填
    if($timu['bitian'])
    {
        $title=" <div class='field-label'>{$timu['id']}. {$timu['title']}(单选)
                        <span class='req'>*</span>
                    </div>";
        if($xuan=='2')
        {
            $title=" <div class='field-label'>{$timu['id']}. {$timu['title']}
                        <span class='req'>*</span>  <span class='qtypetip'>&nbsp;【多选题】</span>
                    </div>";
        }


        $xx_html= "<div class='field ui-field-contain' id='div{$tmid}' req='1' topic='{$tmid}' data-role='fieldcontain' {$type_html}>
                   {$title}
                    {$xx_html}

                    <div class='errorMessage'></div>
                </div>";

    }
    else
    {
        $title=" <div class='field-label'>{$timu['id']}. {$timu['title']}(单选)
                    </div>";


        $xx_html= "<div class='field ui-field-contain' id='div{$tmid}'  topic='{$tmid}' data-role='fieldcontain' {$type_html}>
                   {$title}
                    {$xx_html}

                    <div class='errorMessage'></div>
                </div>";
    }




    return $xx_html;

}



function duoxuan($timu)
{

    $timu=[
                'id'=>5,
                'title'=>'您喜欢哪种材质的珠宝首饰？',
                'xuanxiang'=>['1'=>'贵金属饰品（黄金、铂金、K金、银等）','2'=>'其他金属饰品（合金、钢等）',
                    '3'=>'宝石饰品（钻石、红宝石、蓝宝石、祖母绿、碧玺、水晶等）',
                    '4'=>'玉石类（翡翠、和田玉、玛瑙等）','5'=>'有机宝石（珍珠、珊瑚、琥珀等）' ,
                '6'=>'金镶玉','7'=>'其他'],
                'lieshu' => 1,
                'bitian' => 0,
            ];



    $i=1;
    $tmid=$timu['id'];
    $xx_html='';
    foreach($timu['xuanxiang'] as $key=>$value)
    {
        $html_id=$tmid .'_'.$i;
        $html_lbl=chr(64+$i);
        $xx_html.="
            <div class='ui-checkbox'>
            <span class='jqcheckwrapper'>
                <input type='checkbox' value='{$key}' id='q{$html_id}' name='q{$tmid}' style='display:none;' />
                <a class='jqcheck' href='javascript:;'></a>
            </span>
                <div class='label' for='q{$html_id}'>{$html_lbl}.{$value}</div>
            </div>
            ";
        $i++;
    }






}





function array2xml($arr, $level = 1) {
    $s = $level == 1 ? "<xml>" : '';
    foreach ($arr as $tagname => $value) {
        if (is_numeric($tagname)) {
            $tagname = $value['TagName'];
            unset($value['TagName']);
        }
        if (!is_array($value)) {
            $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
        } else {
            $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
        }
    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
    return $level == 1 ? $s . "</xml>" : $s;
}


/**
 * 随机字符
 * @param int $length 长度
 * @param string $type 类型
 * @param int $convert 转换大小写 1大写 0小写
 * @return string
 */
function random($length=10, $type='letter', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'letter';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}


function ihttp_request($url, $post = '', $extra = array(), $timeout = 60)
{
    $urlset = parse_url($url);
    if (empty($urlset['path']))
    {
        $urlset['path'] = '/';
    }
    if (!empty($urlset['query']))
    {
        $urlset['query'] = "?{$urlset['query']}";
    }
    if (empty($urlset['port']))
    {
        $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
    }
    if (strexists($url, 'https://') && !extension_loaded('openssl'))
    {
        if (!extension_loaded("openssl"))
        {
            die('请开启您PHP环境的openssl');
        }
    }

    if (function_exists('curl_init') && function_exists('curl_exec'))
    {
        $ch = curl_init();
        if (ver_compare(phpversion(), '5.6') >= 0)
        {
             curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
        }
        if (!empty($extra['ip']))
        {
            $extra['Host'] = $urlset['host'];
            $urlset['host'] = $extra['ip'];
            unset($extra['ip']);
        }
        curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

        if ($post)
        {
            if (is_array($post))
            {
                $filepost = false;
                foreach ($post as $name => $value)
                {
                    if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile))
                    {
                        $filepost = true;
                        break;
                    }
                }
                if (!$filepost)
                {
                    $post = http_build_query($post);
                }
            }
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        if (defined('CURL_SSLVERSION_TLSv1')) {
            curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
        if (!empty($extra) && is_array($extra))
        {
            $headers = array();
            foreach ($extra as $opt => $value) {
                if (strexists($opt, 'CURLOPT_')) {
                    curl_setopt($ch, constant($opt), $value);
                } elseif (is_numeric($opt)) {
                    curl_setopt($ch, $opt, $value);
                } else {
                    $headers[] = "{$opt}: {$value}";
                }
            }
            if (!empty($headers)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            }
        }
        $data = curl_exec($ch);
        $status = curl_getinfo($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($errno || empty($data))
        {
            die(json_encode($error));
        }
        else
        {
            return ihttp_response_parse($data);
        }
    }

}



function ihttp_response_parse($data, $chunked = false) {
    $rlt = array();
    $headermeta = explode('HTTP/', $data);
    if (count($headermeta) > 2) {
        $data = 'HTTP/' . array_pop($headermeta);
    }
    $pos = strpos($data, "\r\n\r\n");
    $split1[0] = substr($data, 0, $pos);
    $split1[1] = substr($data, $pos + 4, strlen($data));

    $split2 = explode("\r\n", $split1[0], 2);
    preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches);
    $rlt['code'] = $matches[2];
    $rlt['status'] = $matches[3];
    $rlt['responseline'] = $split2[0];
    $header = explode("\r\n", $split2[1]);
    $isgzip = false;
    $ischunk = false;
    foreach ($header as $v) {
        $pos = strpos($v, ':');
        $key = substr($v, 0, $pos);
        $value = trim(substr($v, $pos + 1));
        if (is_array($rlt['headers'][$key])) {
            $rlt['headers'][$key][] = $value;
        } elseif (!empty($rlt['headers'][$key])) {
            $temp = $rlt['headers'][$key];
            unset($rlt['headers'][$key]);
            $rlt['headers'][$key][] = $temp;
            $rlt['headers'][$key][] = $value;
        } else {
            $rlt['headers'][$key] = $value;
        }
        if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
            $isgzip = true;
        }
        if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
            $ischunk = true;
        }
    }

    $rlt['content'] = $split1[1];

    if($isgzip && function_exists('gzdecode')) {
        $rlt['content'] = gzdecode($rlt['content']);
    }

    $rlt['meta'] = $data;
    if($rlt['code'] == '100') {
        return ihttp_response_parse($rlt['content']);
    }
    return $rlt;
}


function strexists($string, $find) {
    return !(strpos($string, $find) === FALSE);
}

function ver_compare($version1, $version2)
{
    $version1 = str_replace('.', '', $version1);
    $version2 = str_replace('.', '', $version2);
    $oldLength = strlen($version1);
    $newLength = strlen($version2);
    if (is_numeric($version1) && is_numeric($version2))
    {
        if ($oldLength > $newLength)
        {
            $version2 .= str_repeat('0', $oldLength - $newLength);
        }
        if ($newLength > $oldLength)
        {
            $version1 .= str_repeat('0', $newLength - $oldLength);
        }
        $version1 = intval($version1);
        $version2 = intval($version2);
    }
    return version_compare($version1, $version2);
}